<template>
  <v-dialog v-model="isVisible" max-width="600" persistent>
    <v-card>
      <v-card-title class="d-flex align-center">
        <v-icon class="mr-2" :icon="credential ? mdiPencil : mdiPlus" />
        {{ credential ? t('passEdit.dialog.editTitle') : t('passEdit.dialog.addTitle') }}
      </v-card-title>

      <v-card-text>
        <v-form ref="formRef" v-model="isFormValid">
          <v-text-field
            v-model="formData.domain"
            class="mb-3"
            :disabled="!!credential"
            :label="t('passEdit.form.domain')"
            :placeholder="t('passEdit.form.domainPlaceholder')"
            :rules="[rules.required]"
            variant="outlined"
          />

          <v-text-field
            v-model="formData.site_name"
            class="mb-3"
            :label="t('passEdit.form.siteNameOptional')"
            :placeholder="t('passEdit.form.siteNamePlaceholder')"
            variant="outlined"
          />

          <v-text-field
            v-model="formData.username"
            class="mb-3"
            :label="t('passEdit.form.usernameOrEmail')"
            :placeholder="t('passEdit.form.usernameOrEmailPlaceholder')"
            :rules="[rules.required]"
            variant="outlined"
          />

          <v-text-field
            v-model="formData.password"
            :append-inner-icon="showPassword ? mdiEyeOff : mdiEye"
            class="mb-3"
            :label="t('passEdit.form.password')"
            :rules="[rules.required]"
            :type="showPassword ? 'text' : 'password'"
            variant="outlined"
            @click:append-inner="showPassword = !showPassword"
          >
            <template #append>
              <v-btn
                :icon="mdiRefresh"
                size="small"
                :title="t('passEdit.actions.generatePassword')"
                variant="text"
                @click="generatePassword"
              />
            </template>
          </v-text-field>

          <v-switch
            v-model="formData.auto_fill_enabled"
            class="mb-3"
            color="primary"
            hide-details
            :label="t('passEdit.form.autoFillEnabled')"
          />

          <!-- 密码强度指示器 -->
          <div v-if="formData.password" class="mb-3">
            <div class="text-caption mb-1">{{ t('passEdit.strength.title') }}</div>
            <v-progress-linear
              :color="getStrengthColor(passwordStrength.level)"
              height="6"
              :model-value="passwordStrength.score * 25"
              rounded
            />
            <div
              class="text-caption mt-1"
              :class="`text-${getStrengthColor(passwordStrength.level)}`"
            >
              {{ getStrengthText(passwordStrength.level) }}
            </div>
          </div>
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer />
        <v-btn variant="text" @click="closeDialog"> {{ t('passEdit.actions.cancel') }}</v-btn>
        <v-btn color="primary" :disabled="!isFormValid" :loading="isSaving" @click="saveCredential">
          {{ credential ? t('passEdit.actions.update') : t('passEdit.actions.save') }}
        </v-btn>
      </v-card-actions>
    </v-card>

    <!-- 密码生成器对话框 -->
    <v-dialog v-model="showPasswordGenerator" max-width="400">
      <v-card>
        <v-card-title>{{ t('passEdit.generator.title') }}</v-card-title>

        <v-card-text>
          <v-slider
            v-model="passwordLength"
            class="mb-4"
            :label="t('passEdit.generator.lengthLabel')"
            :max="32"
            :min="8"
            :step="1"
            thumb-label
          />

          <v-checkbox
            v-model="includeUppercase"
            class="mb-2"
            hide-details
            :label="t('passEdit.generator.includeUppercase')"
          />

          <v-checkbox
            v-model="includeLowercase"
            class="mb-2"
            hide-details
            :label="t('passEdit.generator.includeLowercase')"
          />

          <v-checkbox
            v-model="includeNumbers"
            class="mb-2"
            hide-details
            :label="t('passEdit.generator.includeNumbers')"
          />

          <v-checkbox
            v-model="includeSymbols"
            class="mb-4"
            hide-details
            :label="t('passEdit.generator.includeSymbols')"
          />

          <v-text-field
            v-model="generatedPassword"
            :append-inner-icon="mdiContentCopy"
            :label="t('passEdit.generator.generatedPassword')"
            readonly
            variant="outlined"
            @click:append-inner="copyGeneratedPassword"
          />
        </v-card-text>

        <v-card-actions>
          <v-btn variant="text" @click="generateNewPassword">
            {{ t('passEdit.generator.regenerate') }}</v-btn
          >
          <v-spacer />
          <v-btn variant="text" @click="showPasswordGenerator = false">
            {{ t('passEdit.actions.cancel') }}</v-btn
          >
          <v-btn color="primary" @click="useGeneratedPassword">
            {{ t('passEdit.generator.useThisPassword') }}</v-btn
          >
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-dialog>
</template>

<script lang="ts" setup>
import { computed, nextTick, ref, watch } from 'vue'
import { mdiContentCopy, mdiEye, mdiEyeOff, mdiPencil, mdiPlus, mdiRefresh } from '@mdi/js'
import { usePasswordManagerStore } from '@/stores/passwordManager'

import { useI18n } from 'vue-i18n'

// 类型定义
interface DecryptedUserCredential {
  _id: string
  id?: number
  domain: string
  site_name?: string | null
  username: string
  password: string
  favicon_url?: string | null
  auto_fill_enabled: boolean
  is_synced: boolean
  server_id?: string | null
  last_used_at?: Date | null
  created_at: Date
  updated_at: Date
}

interface Props {
  modelValue: boolean
  credential?: DecryptedUserCredential | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void

  (e: 'saved'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const { t } = useI18n()

const passwordManagerStore = usePasswordManagerStore()

// 响应式数据
const formRef = ref()
const isFormValid = ref(false)
const isSaving = ref(false)
const showPassword = ref(false)

// 表单数据
const formData = ref({
  domain: '',
  site_name: '',
  username: '',
  password: '',
  auto_fill_enabled: true
})

// 密码生成器
const showPasswordGenerator = ref(false)
const passwordLength = ref(16)
const includeUppercase = ref(true)
const includeLowercase = ref(true)
const includeNumbers = ref(true)
const includeSymbols = ref(true)
const generatedPassword = ref('')

// 密码强度
const passwordStrength = ref({
  score: 0,
  level: 'weak' as 'weak' | 'fair' | 'good' | 'strong',
  feedback: [] as string[]
})

// 验证规则
const rules = {
  required: (value: string) => !!value || t('passEdit.validation.required')
}

// 计算属性
const isVisible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

// 监听对话框显示状态
watch(isVisible, async newValue => {
  if (newValue) {
    await nextTick()
    resetForm()
    if (props.credential) {
      loadCredentialData()
    }
  }
})

// 监听密码变化，检查强度
watch(
  () => formData.value.password,
  async newPassword => {
    if (newPassword) {
      try {
        const strength = await passwordManagerStore.checkPasswordStrength(newPassword)
        if (strength) {
          passwordStrength.value = strength
        }
      } catch (error) {
        console.error('检查密码强度失败:', error)
      }
    } else {
      passwordStrength.value = {
        score: 0,
        level: 'weak',
        feedback: []
      }
    }
  }
)

/**
 * 重置表单
 */
function resetForm(): void {
  formData.value = {
    domain: '',
    site_name: '',
    username: '',
    password: '',
    auto_fill_enabled: true
  }
  showPassword.value = false
  passwordStrength.value = {
    score: 0,
    level: 'weak',
    feedback: []
  }
}

/**
 * 加载凭据数据
 */
function loadCredentialData(): void {
  if (props.credential) {
    formData.value = {
      domain: props.credential.domain,
      site_name: props.credential.site_name || '',
      username: props.credential.username,
      password: props.credential.password,
      auto_fill_enabled: props.credential.auto_fill_enabled
    }
  }
}

/**
 * 保存凭据
 */
async function saveCredential(): Promise<void> {
  if (!isFormValid.value) return

  isSaving.value = true
  try {
    let success: boolean

    if (props.credential) {
      // 更新现有凭据
      success = await passwordManagerStore.updateCredential({
        credentialId: props.credential._id,
        domain: formData.value.domain,
        site_name: formData.value.site_name || '',
        username: formData.value.username,
        password: formData.value.password
      })
    } else {
      // 添加新凭据
      success = await passwordManagerStore.addCredential({
        domain: formData.value.domain,
        site_name: formData.value.site_name || '',
        username: formData.value.username,
        password: formData.value.password
      })
    }

    if (success) {
      emit('saved')
      closeDialog()
    }
  } catch (error) {
    console.error('保存凭据失败:', error)
  } finally {
    isSaving.value = false
  }
}

/**
 * 关闭对话框
 */
function closeDialog(): void {
  isVisible.value = false
}

/**
 * 生成密码
 */
async function generatePassword(): Promise<void> {
  showPasswordGenerator.value = true
  await generateNewPassword()
}

/**
 * 生成新密码
 */
async function generateNewPassword(): Promise<void> {
  try {
    const password = await passwordManagerStore.generatePassword(passwordLength.value)
    if (password) {
      generatedPassword.value = password
    }
  } catch (error) {
    console.error('生成密码失败:', error)
  }
}

/**
 * 使用生成的密码
 */
function useGeneratedPassword(): void {
  formData.value.password = generatedPassword.value
  showPasswordGenerator.value = false
}

/**
 * 复制生成的密码
 */
async function copyGeneratedPassword(): Promise<void> {
  try {
    await navigator.clipboard.writeText(generatedPassword.value)
  } catch (error) {
    console.error('复制失败:', error)
  }
}

/**
 * 获取强度颜色
 */
function getStrengthColor(level: string): string {
  switch (level) {
    case 'weak': {
      return 'error'
    }
    case 'fair': {
      return 'warning'
    }
    case 'good': {
      return 'info'
    }
    case 'strong': {
      return 'success'
    }
    default: {
      return 'grey'
    }
  }
}

/**
 * 获取强度文本
 */
function getStrengthText(level: string): string {
  switch (level) {
    case 'weak': {
      return t('passEdit.strength.level.weak')
    }
    case 'fair': {
      return t('passEdit.strength.level.fair')
    }
    case 'good': {
      return t('passEdit.strength.level.good')
    }
    case 'strong': {
      return t('passEdit.strength.level.strong')
    }
    default: {
      return t('passEdit.strength.level.unknown')
    }
  }
}
</script>

<i18n>
{
  "zhHans": {
    "passEdit": {
      "dialog": {
        "editTitle": "编辑密码",
        "addTitle": "添加密码"
      },
      "form": {
        "domain": "网站域名",
        "domainPlaceholder": "例如: example.com",
        "siteNameOptional": "网站名称（可选）",
        "siteNamePlaceholder": "例如: 示例网站",
        "usernameOrEmail": "用户名/邮箱",
        "usernameOrEmailPlaceholder": "输入用户名或邮箱地址",
        "password": "密码",
        "autoFillEnabled": "启用自动填充"
      },
      "actions": {
        "generatePassword": "生成密码",
        "cancel": "取消",
        "update": "更新",
        "save": "保存"
      },
      "strength": {
        "title": "密码强度",
        "level": {
          "weak": "弱",
          "fair": "一般",
          "good": "良好",
          "strong": "强",
          "unknown": "未知"
        }
      },
      "generator": {
        "title": "生成密码",
        "lengthLabel": "密码长度",
        "includeUppercase": "包含大写字母 (A-Z)",
        "includeLowercase": "包含小写字母 (a-z)",
        "includeNumbers": "包含数字 (0-9)",
        "includeSymbols": "包含符号 (!#$%^&*)",
        "generatedPassword": "生成的密码",
        "regenerate": "重新生成",
        "useThisPassword": "使用此密码"
      },
      "validation": {
        "required": "此字段为必填项"
      }
    }
  },
  "en": {
    "passEdit": {
      "dialog": {
        "editTitle": "Edit Password",
        "addTitle": "Add Password"
      },
      "form": {
        "domain": "Website domain",
        "domainPlaceholder": "e.g. example.com",
        "siteNameOptional": "Site name (optional)",
        "siteNamePlaceholder": "e.g. Sample Site",
        "usernameOrEmail": "Username/Email",
        "usernameOrEmailPlaceholder": "Enter username or email address",
        "password": "Password",
        "autoFillEnabled": "Enable auto-fill"
      },
      "actions": {
        "generatePassword": "Generate password",
        "cancel": "Cancel",
        "update": "Update",
        "save": "Save"
      },
      "strength": {
        "title": "Password strength",
        "level": {
          "weak": "Weak",
          "fair": "Fair",
          "good": "Good",
          "strong": "Strong",
          "unknown": "Unknown"
        }
      },
      "generator": {
        "title": "Generate Password",
        "lengthLabel": "Password length",
        "includeUppercase": "Include uppercase (A-Z)",
        "includeLowercase": "Include lowercase (a-z)",
        "includeNumbers": "Include numbers (0-9)",
        "includeSymbols": "Include symbols (!#$%^&*)",
        "generatedPassword": "Generated password",
        "regenerate": "Regenerate",
        "useThisPassword": "Use this password"
      },
      "validation": {
        "required": "This field is required"
      }
    }
  }
}
</i18n>
